package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住信息Service业务层处理
 * 
 * @author alexis
 * @date 2025-11-01
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住信息
     * 
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住信息列表
     * 
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     * 
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住信息
     * 
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住信息
     * 
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息信息
     * 
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }



    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 1. 检查老人是否已经入住
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus,1);

        Elder elder = elderMapper.selectOne(wrapper);
        if(ObjectUtil.isNotEmpty(elder)){
            throw new BaseException("该老人已经入住");
        }
        //2. 更新床位状态
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或者更新老人信息
        elder=insertOrUpdateElder(bed,checkInApplyDto.getCheckInElderDto());

        //4.新增签约信息
        String number ="HT"+ CodeGenerator.generateContractNumber();
        insertContract(number,elder,checkInApplyDto);


        //5. 新增入住信息
       CheckIn checkIn= insertCheckInInfo(elder,checkInApplyDto);

        //6. 新增入住配置信息
        insertCheckInConfig(checkIn,checkInApplyDto);

    }

    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }


    private CheckIn insertCheckInInfo(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        // 属性拷贝
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkIn);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStatus(0);
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(String number, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();

        // 属性拷贝
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
        contract.setContractNumber(number);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setEndDate(endDate);
        contract.setStartDate(startDate);
        Integer status=startDate.isBefore(LocalDateTime.now()) ? 1:0;
        contract.setStatus(status);
        contractMapper.insert(contract);

    }

    private Elder insertOrUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = new Elder();
        // 属性赋值
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        // 查询老人数据
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo())
                .ne(Elder::getStatus,1);

        Elder elderDB = elderMapper.selectOne(wrapper);
        if(ObjectUtil.isNotEmpty(elderDB)){
            elder.setId(elderDB.getId());
            elderMapper.updateById(elder);
        }else {
            elderMapper.insert(elder);
        }
        return elder;
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 1. 获取入住配置信息
        CheckIn checkIn = checkInMapper.selectById(id);
        LambdaQueryWrapper<CheckInConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn,checkInConfigVo);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //2. 设置老人响应数据
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        // 3.家属响应信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        // 设置签约办理
        LambdaQueryWrapper<Contract> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(wrapper2);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
